#! /usr/bin/python

"""
sets all "name" tags of "node","way" to the specified language
	    ######################
	    # now is the time to change the attributes before they are written to the file

	    # modify "name" according to the rule:
	    #   name:he,name:de,name      # if the others don't exist, take "name"
	    #   name:he,name,name:de,name # "name" may be in the middle of the list
	    #   name:he,name:de           # if "name" does not appear in the list, in will be deleted if it exists
	    srcTags = ["name:en","name","name:he",]
	    dstTag = "name"
"""

import sys
import getopt
import xml.sax
from xml.sax.saxutils import escape, quoteattr
 
class OSMXMLFileParser(xml.sax.ContentHandler):
    def __init__(self, glb_vars):
        #self.glb_vars = glb_vars
	self.nest = ""
	self.curr_tags = None
 
    def startElement(self, name, attrs):
	# do not print tag elemnts.
	# they will be printed on endElement() of parent node.
	if name != "tag":
		#print xml: start of node + all its attributes
		print self.nest+"<"+escape(name),
		if len(attrs)!=0:
			temp = ["%s=%s" % (escape(akey),quoteattr(aval)) for akey,aval in attrs.items()]
			temp = " ".join(temp)
			print temp.encode('utf-8'),
		print ">"
		
	self.nest += " " # increment the nesting level

	if name == 'node' or name == 'way' or name == 'relation':
            assert self.curr_tags == None
	    self.curr_tags = {}
	
        elif name == 'tag':
            assert self.curr_tags != None
            self.curr_tags[attrs['k']] = attrs['v']
	return
 
    def endElement(self, name):
	if name == 'node' or name == 'way' or name == 'relation':
            assert self.curr_tags != None

	    ######################
	    # now is the time to change the attributes before they are written to the file

	    # modify "name" according to the rule:
	    #   name:he,name:de,name      # if the others don't exist, take "name"
	    #   name:he,name,name:de,name # "name" may be in the middle of the list
	    #   name:he,name:de           # if "name" does not appear in the list, in will be deleted if it exists
	    #srcTags = ["name:en","name","name:he"]
	    #dstTag = "name"
	    matchedRep = None
	    for rep in srcTags:
		    if self.curr_tags.has_key(rep):
			matchedRep = rep
			break
	    if matchedRep != None:
		    self.curr_tags[dstTag] = self.curr_tags[matchedRep]
	    else:
		    self.curr_tags.pop(dstTag,0) # remove element from dict, no error if not found
	    ######################

            # print all tags of this element
	    for k,v in self.curr_tags.items():
		    #print self.nest+"<tag k=%s v=%s />" % (quoteattr(k),quoteattr(v))
		    # workaorund...
		    temp = self.nest+"<tag k=%s v=%s />" % (quoteattr(k),quoteattr(v))
		    print temp.encode('utf-8')
		    # workaorund...
	    self.curr_tags = None

	self.nest = self.nest[1:] # decrement the nesting level
	# print </name>, but not for tag element.
	# they will be treated when they parent element ends.
	if name != "tag":
		print self.nest+"</"+escape(name)+">"


######################## main #########################

# parse command line arguments

(opts, args) = getopt.getopt(sys.argv[1:], [], ["dst-tag=","src-tags=","help"])
#print "opts", opts
#print "args", args

dstTag  = "name"            # the tag to be replaced
srcTags = ["name:en"]       # list of tags that should replace dstTag, in order of importance.

for opt_name,opt_val in opts:
	if opt_name == "--dst-tag":
		dstTag = opt_val
	elif opt_name == "--src-tags":
		srcTags = opt_val.split(",")
	elif opt_name == "--help":
		print """
usage: osm_fix_lang.py [options] [input_file.osm]
Reads an osm file and overwrites all --dst-tag tags (e.g. "name") with
the first available tag from --src-tags list (e.g. "name:de,name:en").
If no input file is specified, reads from stdin.
Output is always written to stdout.

  --help     this help message
  --dst-tag tag_key 
             (default value: "name")
             key of the tags to be replaced/deleted by the source tags.
  --src-tags tags_list
             (default value: "name:en")
             comma separated list of tag names. for each node/way/relation, the first existing these 
             tag from the list, will replace dst_tag.

examples:
  replace "name" tags with "name:en" tag.
  if no "name:en" exists and "name" time exists, delete the "name" tag.

       osm_fix_lang.py --dst-tag name --src-tags name:en < in.osm

  replace "name" tags with "name:en" tag.
  if no "name:en", keep the old "name" tag.

       osm_fix_lang.py --dst-tag name --src-tags name:en,name < in.osm

  replace "name" tags with "name:de".
  if no "name:de", try "name:en" and so on.

       osm_fix_lang.py --dst-tag name --src-tags name:de,name:en,name,name:he < in.osm
"""
		exit(0)
		

print >>sys.stderr, "--dst-tags = ",repr(dstTag)
print >>sys.stderr, "--src-tag = ",srcTags




# global variables
glb_vars = {}

if len(args)>0:
	infile = args[0]
	print >>sys.stderr, "reading from:", infile
else:
	infile = sys.stdin
	print >>sys.stderr, "reading from: STDIN"
parser = xml.sax.make_parser()
parser.setContentHandler(OSMXMLFileParser(glb_vars))
print "<?xml version='1.0' encoding='UTF-8'?>"
parser.parse(infile)
